package com.xywh.micro_warehousing.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xw.repo.XEditText;
import com.xywh.micro_warehousing.R;
import com.xywh.micro_warehousing.di.component.DaggerRegisterComponent;
import com.xywh.micro_warehousing.di.module.RegisterModule;
import com.xywh.micro_warehousing.mvp.contract.RegisterContract;
import com.xywh.micro_warehousing.mvp.presenter.RegisterPresenter;
import com.xywh.micro_warehousing.mvp.ui.entity.GetDepart;
import com.xywh.micro_warehousing.mvp.ui.entity.GetIsExistsLoginName;
import com.xywh.micro_warehousing.mvp.ui.entity.Register;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_REGISTER)
public class RegisterActivity extends BaseActivity<RegisterPresenter> implements RegisterContract.View {

    public static final int PICK_REG_VIDEO = 100;
    private static final int REQUEST_CODE_AUTO_DETECT = 100;
    @BindView(R.id.xet_name)
    XEditText xetName;
    @BindView(R.id.xet_phone)
    XEditText xetPhone;
    @BindView(R.id.nice_spinner)
    NiceSpinner niceSpinner;
    @BindView(R.id.xet_username)
    XEditText xetUsername;
    @BindView(R.id.xet_password)
    XEditText xetPassword;
    @BindView(R.id.xet_password_again)
    XEditText xetPasswordAgain;
    @BindView(R.id.img_face_recognition)
    ImageView imgFaceRecognition;
    @BindView(R.id.btn_register)
    Button btnRegister;
    private String mSelectDepartId;
    private String faceImagePath;
    private String groupId;
    private String faceUid = String.valueOf(UUID.randomUUID());
    private BottomDialogUtil mBottomDialogUtilShare;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerRegisterComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .registerModule(new RegisterModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_register; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_register));
//        getRegisterData();
        PhotoUtil.init(getContext(), new FrescoIniter());//第二个参数根据具体依赖库而定

//        groupId = DeviceUtils.getIMEI(this);

        getDepart();
    }

    private void getDepart() {
        mPresenter.getDepart(new HashMap<>());
    }

    @Override
    public void getRegisterDataSuccess(Register entityData) {

        if (entityData.getCode() == 200) {
            showMessage("注册成功");
            killMyself();
        } else {
            showMessage(entityData.getMessage());
            delFaceUser();
        }

    }

    /**
     * 如果后台注册失败后，删除本地人脸数据
     */
    private void delFaceUser() {
        if (!TextUtils.isEmpty(faceUid) && !TextUtils.isEmpty(groupId)) {
//            FaceApi.getInstance().userDelete(faceUid, groupId);
        }
    }

    @Override
    public void getRegisterErrorSuccess(Throwable t) {
        delFaceUser();
    }

    @Override
    public void getIsExistsLoginNameSuccess(GetIsExistsLoginName entityData) {

        if (!entityData.isData()) {
            if (TextUtils.isEmpty(faceImagePath)) {
                shangChuangTuPian();
            } else {
                String imgBase64Str = null;
                try {
                    imgBase64Str = ArmsUtils.fileToBase64(faceImagePath);

                    HashMap<String, String> map = new HashMap<>();
                    map.put("UserName", getXetName());
                    map.put("LoginName", getXetUsername());
                    map.put("LoginPwd", getXetPassword());
                    map.put("MobilePhone", getXetPhone());
                    map.put("FacePicture", imgBase64Str);
                    map.put("FacePicExtension", faceImagePath.substring(faceImagePath.lastIndexOf(".") + 1, faceImagePath.length()));
                    map.put("DepartId", mSelectDepartId);
                    map.put("BaiduFaceId", faceUid);
                    map.put("BaiduFaceToken", faceUid);
                    map.put("BaiduFaceGroup", "default_group");
                    mPresenter.getRegisterData(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        } else {
            showMessage("用户名已存在");
        }
    }

    @Override
    public void getDepartSuccess(GetDepart entityData) {
        if (entityData != null && entityData.getData() != null && entityData.getData().size() > 0) {

            try {
                List<String> dataList = new ArrayList<>();
                for (int i = 0; i < entityData.getData().size(); i++) {
                    dataList.add(entityData.getData().get(i).getDepName());
                }
                niceSpinner.attachDataSource(dataList);
                mSelectDepartId = String.valueOf(entityData.getData().get(0).getDepId());
                niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        mSelectDepartId = String.valueOf(entityData.getData().get(position).getDepId());
                    }
                });
                niceSpinner.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (dataList.size() == 0) {

                            getDepart();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void shangChuangTuPian() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        try {
            btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mBottomDialogUtilShare != null)
                        mBottomDialogUtilShare.dismissDiaolog();

                    PhotoUtil.begin()
                            .setNeedCropWhenOne(true)
                            .setNeedCompress(true)
                            .setMaxSelectCount(1)
                            .setCropMuskOval()
                            //                        .setSelectGif()
                            /*.setFromCamera(false)
                            .setMaxSelectCount(5)
                            .setNeedCropWhenOne(false)
                            .setNeedCompress(true)
                            .setCropRatio(16,9)*/
                            .start(RegisterActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                                @Override
                                public void onFail(String msg, Throwable r, int requestCode) {
                                    LogUtils.debugInfo(msg);
                                }

                                @Override
                                public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                    try {
                                        faceImagePath = compressedPath;
                                        imgFaceRecognition.setImageBitmap(ArmsUtils.getSmallBitmap(faceImagePath));

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }

                                @Override
                                public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                                    //                                refresh1(originalPaths);
                                    LogUtils.debugInfo(String.valueOf(requestCode));

                                }

                                @Override
                                public void onCancel(int requestCode) {
                                    LogUtils.debugInfo(String.valueOf(requestCode));

                                }
                            }));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.cropAvatar(true)
                        .start(RegisterActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    faceImagePath = compressedPath;
                                    imgFaceRecognition.setImageBitmap(ArmsUtils.getSmallBitmap(faceImagePath));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(getContext(), root);

        mBottomDialogUtilShare.showDiaolog();


    }

    private String getXetName() {
        return xetName.getText().toString().trim();
    }

    private String getXetUsername() {
        return xetUsername.getText().toString().trim();
    }

    private String getXetPassword() {
        return xetPassword.getText().toString().trim();
    }

    private String getXetPhone() {
        return xetPhone.getText().toString().trim();
    }

    private void getRegisterData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getRegisterData(map);
    }

    @OnClick({R.id.img_face_recognition, R.id.btn_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_face_recognition:
                shangChuangTuPian();
                break;
            case R.id.btn_register:

                if (TextUtils.isEmpty(getXetName())) {

                    showMessage("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(getXetPhone())) {

                    showMessage("请输入电话");
                    return;
                }
                if (TextUtils.isEmpty(getXetUsername())) {

                    showMessage("用户名");
                    return;
                }
                if (TextUtils.isEmpty(getXetPassword())) {

                    showMessage("请输入密码");
                    return;
                }
                if (TextUtils.isEmpty(getXetPasswordAgain())) {

                    showMessage("请输入确认密码");
                    return;
                }
                if (!getXetPassword().equals(getXetPasswordAgain())) {
                    showMessage("两次输入的密码不一致");
                    return;
                }
                if (TextUtils.isEmpty(mSelectDepartId)) {
                    showMessage("请选择部门");
                    return;
                }

                if (TextUtils.isEmpty(faceImagePath)) {
                    shangChuangTuPian();
                    showMessage("请上传人脸图片");
                    return;
                }

                //注册的时候验证服务器是否存在用户
                HashMap<String, String> map = new HashMap<>();
                map.put("loginName", getXetUsername());
                mPresenter.getIsExistsLoginName(map);
                break;
        }
    }

    private String getXetPasswordAgain() {
        return xetPasswordAgain.getText().toString().trim();
    }

    private void toRegDetectActivity() {
        Intent intent = new Intent(getContext(), FaceRecognitionActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("face_type", "register");
        intent.putExtras(bundle);

        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101 && data != null) {
            faceImagePath = data.getStringExtra("file_path");
//            LogUtils.debugEInfo("faceImagePath==" + faceImagePath.substring(faceImagePath.lastIndexOf(".") + 1, faceImagePath.length()));
            Bitmap bitmap = BitmapFactory.decodeFile(faceImagePath);
            imgFaceRecognition.setImageBitmap(bitmap);
        } else if (resultCode == 100 && data != null) {

            faceUid = data.getStringExtra("uid");
            faceImagePath = data.getStringExtra("file_path");
            LogUtils.debugEInfo("faceImagePath==" + faceImagePath);
//            LogUtils.debugEInfo("faceImagePath==" + faceImagePath.substring(faceImagePath.lastIndexOf(".") + 1, faceImagePath.length()));
            Bitmap bitmap = BitmapFactory.decodeFile(faceImagePath);
            imgFaceRecognition.setImageBitmap(bitmap);


            String imgBase64Str = null;
            try {
                imgBase64Str = ArmsUtils.fileToBase64(faceImagePath);

                HashMap<String, String> map = new HashMap<>();
                map.put("UserName", getXetName());
                map.put("LoginName", getXetUsername());
                map.put("LoginPwd", getXetPassword());
                map.put("MobilePhone", getXetPhone());
                map.put("FacePicture", imgBase64Str);
                map.put("FacePicExtension", faceImagePath.substring(faceImagePath.lastIndexOf(".") + 1, faceImagePath.length()));
                map.put("DepartId", mSelectDepartId);
                map.put("BaiduFaceId", faceUid);
                map.put("BaiduFaceToken", faceUid);
                map.put("BaiduFaceGroup", "default_group");
                mPresenter.getRegisterData(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            PhotoUtil.onActivityResult(this, requestCode, resultCode, data);

        }
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }
}
